<template>
  <section>
    <!--工具条：关键字查询 + 新增-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">关键字查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <!-- 列表展示
      el-table -- elementUi提供的表格组件
        :data="employees"               -- 绑定列表数据
        highlight-current-row             -- 当前行高亮
        v-loading="listLoading"           -- 忙等框=加载框
        @selection-change="selsChange"    -- 选项改变会触发
        style="width: 100%;"              -- 占屏幕宽度
      el-table-column -- 表格的列
        type="selection"  --  选项
        type="index"      --  编号
        width="55"        --  当前列的宽度
        prop="name"       --  显示属性的值：属性值必须与后端json数据中的对象的key值一致
        label="姓名"      -- 标签
        sortable          -- 可排序
     -->
    <el-table :data="employees" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="username" label="名称" width="100">
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="140">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="140">
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="60">
      </el-table-column>
      <el-table-column prop="state" label="状态" width="80" sortable>
        <!-- 自定义模板：通过scope可以获取到当前行对象：scope.row -->
        <template scope="scope">
          <span style="color: green" v-if="scope.row.state==1">启用</span>
          <span style="color: red" v-else-if="scope.row.state==0">禁用</span>
        </template>
      </el-table-column>
      <el-table-column prop="department.name" label="所属部门" width="120" sortable>
      </el-table-column>
      <el-table-column prop="shop_id" label="员工类型" width="120" sortable>
        <!-- 自定义模板：通过scope可以获取到当前行对象：scope.row -->
        <template scope="scope">
          <span style="color: green" v-if="!scope.row.shop_id">系统管理员</span>
          <span style="color: blue" v-else-if="scope.row.shop_id && !scope.row.shop.adminId && scope.row.shop.adminId!=scope.row.shop_id">店员</span>
          <span style="color: red" v-else>店长</span>
        </template>
      </el-table-column>

      <el-table-column   prop="role.name" label="角色" width="120" sortable>
      </el-table-column>


      <el-table-column label="操作">
        <template scope="scope">
          <!-- elmentUi提供的按钮：size表示大小，type表示按钮颜色
           scope.$index：当前行下标
           scope.row：当前行对象
           -->
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove"
                 :disabled="this.sels.length===0">批量删除</el-button>
      <!--
        el-pagination -- 显示分页栏
          layout="prev, pager, next"                -- 布局【上一页，当前页，下一页】
          @current-change="handleCurrentChange"     -- 点击某一页的时候会处罚
          :page-size="queryParams.pageSize"         -- 绑定每页显示的条数
          :total="pageParams.totals"                -- 绑定总条数
          :current-page="queryParams.currentPage"   -- 绑定当前页
          style="float:right;"                      -- 显示在右边
      -->
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize" :total="totals" :current-page="currentPage" style="float:right;">
      </el-pagination>
    </el-col>

    <!-- 添加或修改的模态框
     el-dialog - elementUi提供的对话框 = 模态框
      :title="title" - 动态改变标题
      :visible.sync="saveFormVisible"  - 模态框的显示状态
      :close-on-click-modal="false" - 关闭模态框只能通过模态框的x关闭，点击空白处不能关闭模态框
     el-form - 表单
      :model="saveForm" - 绑定表单对象
      label-width="80px" - 标签宽度
      :rules="saveFormRules" - 验证规则
      ref="saveForm" - 为当前模态框取名
        prop="name" - 如果当前字段要验证，就必须写，出现*
        auto-complete="off" - 不自动提示
     -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="saveForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="saveForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="saveForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="saveForm.password" type="password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="saveForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-select v-model="saveForm.department_id" placeholder="请选择" clearable>
            <el-option v-for="item in departments"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <!-- 员工可以选择多个角色：他们是多对多关系 - 所以有中间表 -->
          <!-- 这里我们设计的是一个员工选一个角色 -->
          <el-select v-model="saveForm.role_id" value-key="id" placeholder="请选择" clearable>
            <el-option
                v-for="item in roles"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
export default {
  data() {
    return {
      //分页显示所属数据
      employees: [],
      listLoading: false,
      currentPage: 1,
      pageSize: 5,
      totals: 0,

      //高级查询所需数据
      keyword: null,

      //多条数据选中
      sels: [],//列表选中列

      //添加或修改数据
      saveFormVisible: false,//添加或修改界面是否显示
      saveLoading: false,
      title: null,
      saveFormRules: {
        username: [
          { required: true, message: '请输入员工名称', trigger: 'blur' }
        ]
      },
      saveForm: {
        id: null,
        username: '',
        phone: '',
        email: '',
        age: '',
        state: 1,
        department: null,
        department_id: null,
        //为员工添加或修改角色
        role_id: null
      },
      //员工所属部门
      departments: [],
      //为员工分配角色
      roles: []
    }
  },
  methods: {

    //获取员工列表
    getEmployees() {
      let paras = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true;
      this.$http.post("/employee",paras).then(res => {
        this.totals = res.data.totals;
        this.employees = res.data.data;
        this.listLoading = false;
      }).catch(res => {
        this.$message.error("获取分页数据失败!!!");
      })
    },

    //关键字查询
    keywordQuery(){
      this.currentPage = 1;
      this.getEmployees();
    },

    //分页查询 - 点击某一页查询
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getEmployees();
    },

    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/employee/" + row.id).then(res => {
          this.listLoading = false;
          if(res.data.success){
            //计算总页数
            let totalPage = this.totals%this.pageSize==0?this.totals/this.pageSize
                :Math.ceil(this.totals/this.pageSize);
            if(this.currentPage > 1 && this.currentPage==totalPage && (this.totals-1)%this.pageSize==0){
              this.currentPage = this.currentPage - 1;
            }
            this.getEmployees();
          }else{
            this.$message.error("删除失败【500】");
          }
        }).catch(res => {
          this.$message.error("系统错误【400,404】");
        })
      }).catch(() => {
        //确认框点击取消之后走这里
      });
    },

    //点击修改按钮弹出模态框
    handleEdit: function (index, row) {
      this.title = "编辑";
      this.saveForm = Object.assign({}, row);
      this.getRoles();
      this.getDepartments();
      this.saveFormVisible = true;
    },

    //点击添加按钮弹出模态框
    handleAdd: function () {
      this.title = "添加";
      this.saveForm = {
        id: null,
        username: '',
        phone: '',
        email: '',
        age: '',
        state: 1,
        department: null,
        department_id: null,
        role_id: null
      };
      this.getRoles();
      this.getDepartments();
      this.saveFormVisible = true;
    },

    //点击对话框提交数据
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let paras = Object.assign({}, this.saveForm);

            this.$http.put("/employee",paras).then(res => {
              this.saveFormVisible = false;
              this.saveLoading = false;
              if(res.data.success){
                this.$message.success("操作成功");
                this.refresh();
                this.getEmployees();
              }else{
                this.$message.error("操作失败【500】");
              }
            }).catch(res => {
              this.$message.error("系统错误【400,404】");
            })
          });
        }
      });
    },

    selsChange: function (sels) {
      this.sels = sels;
    },

    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/employee",ids).then(res => {
          this.listLoading = false;
          if(res.data.success){
            this.currentPage = 1;
            this.getEmployees();
          }else{
            this.$message.error("批量删除失败【500】");
          }
        }).catch(res => {
          this.$message.error("系统错误【400,404】");
        })
      }).catch(() => {
      });
    },

    getDepartments(){
      this.$http.get("/department").then(res => {
        this.departments = res.data;
      })
    },

    getRoles(){
      this.$http.get("/role").then(res => {
        this.roles = res.data;
      })
    },
    refresh(){
      let l=localStorage.getItem("logininfo")
      this.$http.post("/refresh/"+l).then(res => {
        //将获取的对象 通过数据 分开
        let {logininfo,menus,permissions} = res.data.resultObj;
        console.log(token);
        console.log(res);
        console.log(logininfo)
        //还得是用这个来解析
        console.log(JSON.stringify(logininfo))
        this.loginInfo.username=username;
        this.loginInfo.password=password;
        localStorage.setItem("Utoken",token);
        localStorage.setItem("logininfo",JSON.stringify(logininfo));//这步是将后端获取的数据表单 存在这个localStorge中
        //拿到的是一个对象，需要转成json格式字符串
        localStorage.setItem("menus",JSON.stringify(menus));
        localStorage.setItem("permissions",JSON.stringify(permissions));
        //把数据刷新完之后刷新页面
        location.reload();
      })
    },
  },

  mounted() {
    //分页查询 - 页面一加载查询
    this.getEmployees();
  }
}

</script>

<style scoped>

</style>